/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			FavoritePatient.java
 * Description:		This is the activity for which
 * 					is responsible for showing the
 * 					users favorite patients.
 * 
 * Responsible
 * =================================================
 * Name:			Vinnie Juul
 * Study number:	09767
 */

package dk.iha.toksEditor;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FavoritePatient extends ListActivity {
	/**
	 * Attributes for this class
	 */
	private ListView mPatientListView;
	private ArrayList<Patient> patienList;
	private DataBaseConnection DBConnection;
	private FavoritePatientAdapter fpAdapter;
	private Boolean showCheckBox;
	private AlertDialog dialog = null;
	private Button canceled;
    private Button remove;
	
	/**
	 * Attributes for AsyncTask 
	 */
	public final String LOAD_PATIENTS = "loadPatients";
	public final String REMOVE_PATIENS = "1";
	public final String ADD_PATIENTS = "2";
	public String asyncCaller;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DBConnection = new DataBaseConnection(new User(this));
		patienList = new ArrayList<Patient>();
		showCheckBox = false;
		setContentView(R.layout.favorite_patients_view);
		mPatientListView = getListView();
		fpAdapter = new FavoritePatientAdapter(getApplicationContext(), R.layout.favorite_patients_row, patienList);
		mPatientListView.setAdapter(fpAdapter);
		
		canceled = (Button)findViewById(R.id.canceledButton);
        remove = (Button)findViewById(R.id.removeButton);
		
		TextView headline = (TextView)findViewById(R.id.FavoritePatientList);
		headline.setText(getText(R.string.FavoritePatientHeadline));
       
		getFavoritePatients();
	}
	
	@Override
	public void onBackPressed() {
	    if(showCheckBox){
	        showCheckBox = false;
	        fpAdapter.notifyDataSetChanged();
	    }else{
	        super.onBackPressed();
	    }
	}
	
	@Override
	protected void onResume() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		if(prefs.getBoolean("checkboxPref", false))
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		
		else
		{
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		super.onResume();
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle state) {
		super.onRestoreInstanceState(state);
		showCheckBox = state.getBoolean("ShowCheckBox", false);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean("ShowCheckBox", showCheckBox);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{		
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent();
		intent.putExtra("patient",patienList.get(position));
		setResult(RESULT_OK, intent);
		finish();
	}
	
	@Override
	public boolean onPrepareOptionsMenu (Menu menu) {
	    if (showCheckBox){
	        menu.getItem(1).setEnabled(false);
	        menu.getItem(0).setEnabled(false);
	    }else{
	    	menu.getItem(1).setEnabled(true);
	    	menu.getItem(0).setEnabled(true);
	    }
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.remove:
	        		showCheckBox = true;
	        		showRemoveButtons();
	        		fpAdapter.notifyDataSetChanged();
	            return true;
	        case R.id.add:
	        	showCheckBox = false;
	        	fpAdapter.notifyDataSetChanged();
	        	addFavoritPatient();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.favorites_patients_menu, menu);
	    return true;
	}
	
	/**
	 * Make a dialog to enter CPR for the patient which should be added to list
	 * Save the patient on database
	 */
	private void addFavoritPatient(){
		LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.add_favorite_patient_dialog, null); 
		dialog = new AlertDialog.Builder(this)
        .setIcon(R.drawable.write_comment_white_icon)
        .setTitle(R.string.FavoritePatientWriteCpr)
        .setView(textEntryView)
        .setPositiveButton(R.string.generalSaveBtn, new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface mdialog, int whichButton) 
        	{
        		EditText text = (EditText)dialog.findViewById(R.id.addFavoritPatientEditText);
        		if(text.getText().length() == 10){
        			asyncCaller = ADD_PATIENTS;
        			AsyncDBConnection asyncDBC = new AsyncDBConnection();
        			asyncDBC.execute(ADD_PATIENTS, text.getText().toString());
        		}else{
        			Toast.makeText(FavoritePatient.this, R.string.FavoritePatientCprToShort, Toast.LENGTH_SHORT).show();
        		}
            }
         })
         .setNegativeButton(R.string.generalCancelBtn, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) 
             {

             }
         })
         .create();
		
		dialog.show();
		
		(new Handler()).postDelayed(new Runnable() {

            public void run() 
            {
		        EditText comments = (EditText)dialog.findViewById(R.id.addFavoritPatientEditText);
		
		        comments.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
		        comments.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
            }
        }, 0);
	}
	
	/**
	 * Remove the selected patient from list
	 * @param view - button view
	 */
	public void removeSelected(View view){
		asyncCaller = REMOVE_PATIENS;
		AsyncDBConnection asyncDBC = new AsyncDBConnection();
		asyncDBC.execute(REMOVE_PATIENS); 
	}
	
	/**
	 * Cancel the removing of patient from list
	 * @param View - button view
	 */
	public void canceled(View View)
	{
		showCheckBox = false;
		showRemoveButtons();
		fpAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Show the button used when selecting patients to be removed
	 * from list.
	 * The button is only visible if showCheckBox is true
	 */
	public void showRemoveButtons(){
		if(canceled != null && remove != null){
			if(showCheckBox){
	        	canceled.setVisibility(View.VISIBLE);
				remove.setVisibility(View.VISIBLE);
	        }
		}
	}

	/**
	 * Create a list of favorite patients by getting the patients from the database
	 */
	private void getFavoritePatients() {
		asyncCaller = LOAD_PATIENTS;
		AsyncDBConnection asyncDBC = new AsyncDBConnection();
		asyncDBC.execute(LOAD_PATIENTS);    	
	}
	
	/**
	 * Class to create custom listview
	 * @author Vinnie Juul
	 *
	 */
	private class FavoritePatientAdapter extends ArrayAdapter<Patient> {
		private ArrayList<Patient> mItems;
		public FavoritePatientAdapter(Context context, int textViewResourceId,
				ArrayList<Patient> items) {
			super(context, textViewResourceId, items);
			mItems = items;
		}
		
		 @Override
	     public View getView(final int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            v = vi.inflate(R.layout.favorite_patients_row, null);
	        }
	        Patient FP = mItems.get(position);
	        if(FP != null){
	        	TextView name = (TextView)v.findViewById(R.id.NameTextView);
	           	TextView cpr = (TextView)v.findViewById(R.id.CprTextView);
	           	if(name != null){
	           		name.setText(FP.getName());
	           	}
	           	if(cpr != null){
	           		cpr.setText(FP.getEasyCPR());
	           	}
	        }      
	                
	        final CheckBox box = (CheckBox)v.findViewById(R.id.RemoveCheckBox);
	              
			if(showCheckBox == true){
				box.setVisibility(View.VISIBLE);
				box.setChecked(FP.getIsChecked());
			}else{
				box.setVisibility(View.INVISIBLE);
				canceled.setVisibility(View.GONE);
				remove.setVisibility(View.GONE);
			}
	                
	        box.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(box.isChecked()){
						patienList.get(position).setIsChecked(true);
					}else{
						patienList.get(position).setIsChecked(false);
					}
				}
			});
							
           	return v;
		 }
	}
	
	/**
	 * Use to run function calls asynchronous
	 * @author Vinnie Juul
	 *
	 */
	private class AsyncDBConnection extends AsyncTask<String, Integer, Boolean>
	{
		private boolean succeded = false;
		private boolean emptyList = false;
		private ProgressDialog mpd;

		@Override
		protected void onPreExecute() {
			if(asyncCaller.equals(LOAD_PATIENTS)){
				mpd = ProgressDialog.show(FavoritePatient.this, getString(R.string.FavoritePatientProgressDialogTitle), getString(R.string.FavoritePatientProgressDialogTextLoad), true, true);	
				
			}else if(asyncCaller.equals(REMOVE_PATIENS)){
				mpd = ProgressDialog.show(FavoritePatient.this, getString(R.string.FavoritePatientProgressDialogTitle), getString(R.string.FavoritePatientProgressDialogTextRemove), true, true);	
			}
			else if(asyncCaller.equals(ADD_PATIENTS)){
				mpd = ProgressDialog.show(FavoritePatient.this, getString(R.string.FavoritePatientProgressDialogTitle), getString(R.string.FavoritePatientProgressDialogTextAdd), true, true);	
			}
			
			mpd.setOnCancelListener(new OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					Intent intent = new Intent();
					setResult(RESULT_CANCELED, intent);
					finish();
				}
			});
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			if(params[0].equals(LOAD_PATIENTS)){
				succeded = DBConnection.listFavorites(patienList);
				if(patienList.size() == 0){
					succeded = false;
				}
			}else if(params[0].equals(REMOVE_PATIENS)){
				succeded = true;
				for(int i = 0; i < patienList.size(); i++){
					if(patienList.get(i).getIsChecked() == true){
							if(DBConnection.deleteFromFavorites(patienList.get(i))){
								patienList.remove(i);
								i--;
							}else{
								succeded = false;
							}
					}
				}
				showCheckBox = false;
				if(patienList.size() == 0){
					emptyList = true;
				}
			}else if(params[0].equals(ADD_PATIENTS)){
				Patient FP = DBConnection.patientInformation(params[1]);
             	if(FP != null){
             		if(DBConnection.addToFavorites(FP)){
	             		patienList.add(FP);
             		}
             	}
             	else{
             		Toast.makeText(FavoritePatient.this, R.string.MainViewPatientNoExist, Toast.LENGTH_SHORT).show();
             	}
			}
			return succeded;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			mpd.dismiss();
			fpAdapter.notifyDataSetChanged();
			if(asyncCaller.equals(LOAD_PATIENTS) && succeded == false)
			{
				setResult(RESULT_CANCELED, new Intent());
				finish();
				Toast.makeText(getApplicationContext(), getString(R.string.FavoritsConnectionErrorMessage), Toast.LENGTH_SHORT).show();
			}else if(asyncCaller.equals(REMOVE_PATIENS) && emptyList == true)
			{
				setResult(RESULT_CANCELED, new Intent());
				finish();
				Toast.makeText(getApplicationContext(), getString(R.string.FavoritsNoFavoritsLeftMessage), Toast.LENGTH_SHORT).show();
			}
			
			super.onPostExecute(result);
		}
	}
}
